package main.api;

import main.ResponseHelper;
import main.database.AudioHelper;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class AudioApi {
    @PostMapping("/api/addaudio")
    public ResponseEntity<?> addAudio(HttpServletRequest request) {
        String result;
        String cid = null, reader = null, source = null;
        Map<String, String[]> map = request.getParameterMap();
        if (map.containsKey("cid")) {
            cid = map.get("cid")[0].trim();
        }
        if (map.containsKey("reader")) {
            reader = map.get("reader")[0].trim();
        }
        if (map.containsKey("source")) {
            source = map.get("source")[0].trim();
        }

        if (cid == null || cid.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "没有提供目标小说的id").toString();
        }
        else if (reader == null || reader.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "没有提供演播者的名字").toString();
        }
        else if (source == null || source.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "没有提供平台名字").toString();
        }
        else if (AudioHelper.isAudioExist(cid, reader, source)) {
            result = ResponseHelper.createBasicJsonObject(404, "同样内容的记录已经存在").toString();
        }
        else {
            AudioHelper.addRecord(cid, reader, source);
            result = ResponseHelper.createBasicJsonObject(200, "ok").toString();
        }

        return ResponseEntity.ok(result);
    }
}
